import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

// 配置NProgress
NProgress.configure({ showSpinner: false })

// 基础路由（无需权限）
const constantRoutes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/index.vue'),
    meta: { title: '登录', hidden: true }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/register/index.vue'),
    meta: { title: '注册', hidden: true }
  },
  {
    path: '/404',
    name: '404',
    component: () => import('@/views/error/404.vue'),
    meta: { title: '404', hidden: true }
  }
]

// 动态路由（需要权限）
export const asyncRoutes = [
  {
    path: '/',
    component: () => import('@/layout/index.vue'),
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/dashboard/index.vue'),
        meta: { title: '首页', icon: 'House', roles: ['admin', 'user'] }
      }
    ]
  },
  {
    path: '/system',
    component: () => import('@/layout/index.vue'),
    name: 'System',
    meta: {
      title: '系统管理',
      icon: 'Setting',
      roles: ['admin'],
      alwaysShow: true
    },
    children: [
      {
        path: 'user',
        name: 'SystemUser',
        component: () => import('@/views/system/user/index.vue'),
        meta: { title: '用户管理', icon: 'User', roles: ['admin'] }
      },
      {
        path: 'role',
        name: 'SystemRole',
        component: () => import('@/views/system/role/index.vue'),
        meta: { title: '角色管理', icon: 'UserFilled', roles: ['admin'] }
      },
      {
        path: 'menu',
        name: 'SystemMenu',
        component: () => import('@/views/system/menu/index.vue'),
        meta: { title: '菜单管理', icon: 'Menu', roles: ['admin'] }
      },
      {
        path: 'permission',
        name: 'SystemPermission',
        component: () => import('@/views/system/permission/index.vue'),
        meta: { title: '权限管理', icon: 'Key', roles: ['admin'] }
      }
    ]
  },
  {
    path: '/api',
    component: () => import('@/layout/index.vue'),
    name: 'ApiManagement',
    meta: {
      title: 'API管理',
      icon: 'Connection',
      roles: ['admin'],
      alwaysShow: true
    },
    children: [
      {
        path: 'list',
        name: 'ApiList',
        component: () => import('@/views/api/list/index.vue'),
        meta: { title: 'API接口管理', icon: 'Document', roles: ['admin'] }
      },

    ]
  },
  {
    path: '/profile',
    component: () => import('@/layout/index.vue'),
    children: [
      {
        path: '',
        name: 'Profile',
        component: () => import('@/views/profile/index.vue'),
        meta: { title: '个人中心', icon: 'User', roles: ['admin', 'user'] }
      }
    ]
  },
  {
    path: '/demo',
    component: () => import('@/layout/index.vue'),
    name: 'Demo',
    meta: {
      title: '功能演示',
      icon: 'Monitor',
      roles: ['admin', 'user'],
      alwaysShow: true
    },
    children: [
      {
        path: 'permission',
        name: 'PermissionDemo',
        component: () => import('@/views/demo/permission.vue'),
        meta: { title: '权限演示', icon: 'Key', roles: ['admin', 'user'] }
      },
      {
        path: 'routes',
        name: 'RoutesDebug',
        component: () => import('@/views/debug/routes.vue'),
        meta: { title: '路由调试', icon: 'Bug', roles: ['admin'] }
      },
      {
        path: 'mobile-test',
        name: 'MobileTest',
        component: () => import('@/views/test/mobile-components.vue'),
        meta: { title: '移动端测试', icon: 'Monitor', roles: ['admin'] }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes: [
    ...constantRoutes,
    ...asyncRoutes,
    { path: '/:pathMatch(.*)*', redirect: '/404' }
  ]
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  NProgress.start()
  
  const userStore = useUserStore()
  const token = userStore.token
  
  if (token) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      // 检查是否已获取用户信息
      if (!userStore.userInfo.id) {
        try {
          await userStore.getUserInfo()
          // 生成可访问的路由列表（用于侧边栏显示）
          await userStore.generateRoutes()
          next()
        } catch (error) {
          console.error('获取用户信息失败:', error)
          await userStore.logout()
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      } else {
        // 检查当前路由权限
        const hasPermission = userStore.checkRoutePermission(to)
        if (hasPermission) {
          next()
        } else {
          next('/404')
          NProgress.done()
        }
      }
    }
  } else {
    // 允许访问登录页和注册页
    if (to.path === '/login' || to.path === '/register') {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})

export default router
